const config = require('_/config');
const request = require('request');

// 获取openid
exports.getOpenId = (code) => {
  const url =  `https://api.weixin.qq.com/sns/jscode2session?appid=${config.wx.appId}&secret=${config.wx.appSecret}&js_code=${code}&grant_type=authorization_code`;
  return new Promise((resolve, reject) => {
    request(url, (error, response, body) => {
      if(response.statusCode === 200) {
        resolve(body)
      }else {
        reject(error)
      }
    });
  })
}

// 获取小程序全局唯一后台接口调用凭据(https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html)
exports.getToken = () => {
  const url =  `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.wx.appId}&secret=${config.wx.appSecret}`;
  return new Promise((resolve, reject) => {
    request(url, (error, response, body) => {
      if(response.statusCode === 200) {
        resolve(body)
      }else {
        reject(error)
      }
    });
  })
}

// 检查一段文本是否含有违法违规内容(https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html#method-http)
exports.msgCheck = (access_token, openid, content) => {
  const url =  `https://api.weixin.qq.com/wxa/msg_sec_check?access_token=${access_token}`;
  return new Promise((resolve, reject) => {
    request({
      url, 
      method: 'POST', 
      json: true,
      headers: {
        "content-type": "application/json; charset=UTF-8",
      },
      body: {
        version: 2,
        openid,
        scene: 2,
        content
      }
    }, (error, response, body) => {
      if(response.statusCode === 200) {
        resolve(body)
      }else {
        reject(error)
      }
    });
  })
}